package com.pay.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.pay.jwt.JWT;

import cn.hutool.core.util.StrUtil;

/**
 * token的一些工具类
 * @author tianpeng
 *
 */
public class TokenUtils {

	
	
	/**
	 * 取得登录的id
	 * @param request
	 * @return
	 */
	public static Integer getLoginId(HttpServletRequest request) {
		String token = getToken(request);
		if(StrUtil.isBlank(token)) {
			return -1 ;
		}
		
		Login login = JWT.unsign(token, Login.class);
		if(login == null) {
			return -1 ;
		}
		
		return login.getId() ;
	}
	
	/**
	 * 从request中获取token
	 * @param request
	 * @return
	 */
	public static String getToken(HttpServletRequest request) {
		//先从头里面取
		String token = request.getHeader("token") ;
		if(StrUtil.isNotBlank(token)) {
			return token ;
		}
		
		/**
		 * 再从cookie里面取
		 */
		if(token == null) {
			Cookie[] cookies = request.getCookies();
			if(cookies != null) {
				for (Cookie cookie : cookies) {
					if(cookie.getName().equals("token")) {
						token = cookie.getValue() ;
						return token ;
					}
				}
			}
		}
		
		return null ;
	}
	
	/**
	 * 取得登录的merchant_id
	 * @param request
	 * @return
	 */
	public static Integer getMerchantLoginId(HttpServletRequest request) {
		String token = getMerchantToken(request);
		if(StrUtil.isBlank(token)) {
			return -1 ;
		}
		
		Login login = JWT.unsign(token, Login.class);
		if(login == null) {
			return -1 ;
		}
		
		return login.getId() ;
	}
	
	/**
	 * 从request中获取merchant_token
	 * @param request
	 * @return
	 */
	public static String getMerchantToken(HttpServletRequest request) {
		//先从头里面取
		String token = request.getHeader("merchant_token") ;
		if(StrUtil.isNotBlank(token)) {
			return token ;
		}
		
		/**
		 * 再从cookie里面取
		 */
		if(token == null) {
			Cookie[] cookies = request.getCookies();
			if(cookies != null) {
				for (Cookie cookie : cookies) {
					if(cookie.getName().equals("merchant_token")) {
						token = cookie.getValue() ;
						return token ;
					}
				}
			}
		}
		
		return null ;
	}
}
